/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.shwread.android.ui.page;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.NewActionHelp;
import com.ciko.code.logic.bean.ContactBean;
import com.ciko.code.logic.bean.ContactSuperBean;
import com.ciko.code.logic.dao.ContactBookInfoDao;
import com.ciko.code.logic.dao.ContactGroupDao;
import com.ciko.code.utils.PerferencesUtil;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.AreaSelectActivity;
import com.shwread.android.qysw.activity.CommonWebActivity;
import com.shwread.android.qysw.activity.ContactGroupActivity;
import com.shwread.android.qysw.activity.ContactSearchActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw10000193.R;
import com.shwread.android.ui.customview.MyListView;
import com.shwread.android.ui.page.chat.SessionPage;
import com.shwread.android.ui.page.chat.adapter.AreaAdapterForDB;
import com.shwread.android.ui.page.chat.adapter.AreaAdapterForNet;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.greendao.gen.GreendaoDBManager;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.AreaBean;
import logic.bean.AreaBean2;
import logic.bean.AreaBeanModle;
import logic.bean.ContactYellowPageInfo;
import logic.constants.DefaultConsts;

public class NewContactsPage
        extends
        AbstractUIPage<MainActivity>
        implements
        OnClickListener {
    private ProgressDialog progressDialog;
    private static final int PROGRESS_SHOW = 111;
    private static final int PROGRESS_HIDE = 112;
    private static final int REFRESH_DATA = 113;
    public static NewContactsPage instance;
    private PullToRefreshScrollView contentView;
    private MyListView listView;
    private TextView tvSearch;
    private RelativeLayout rlChatGroup, rlYellowPage;
    private String ypUrl;
    private static long lastTimeStamp = 0;
    private AreaBean newAreaBean;
    private static long contactLastTimeStamp = 0;
    private PerferencesUtil utils;

    private List<ContactSuperBean> groups = new ArrayList<>();
    private ContactGroupDao groupDao;
    private ContactBookInfoDao addressBookInfoDao;

    public NewContactsPage(MainActivity t) {
        super(t);
    }

    public static NewContactsPage getInstance(MainActivity t) {
        if (instance == null) instance = new NewContactsPage(t);
        return instance;
    }

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) return curMyView;
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.new_chat_contact, null);
        lastTimeStamp = QyreaderPerferencesUtil.getInstance(context, "0").getAreaLastTimeStamp();
        utils = PerferencesUtil.getInstance(context);
        findView();
        initData();
        setListener();

        return curMyView;
    }

    private void initData() {
        groupDao = ContactGroupDao.getInstance(context);
        addressBookInfoDao = ContactBookInfoDao.getInstance(context);
        NewActionHelp.qryEnterpriseYellowPage(context, new GetYellowPageHandler());
        if (lastTimeStamp == 0) {
            NewActionHelp.qryEnterpriseAreaCompanyList(context, 0, new EnterpriseAreaCompanyListHandler());
        } else {
            NewActionHelp.qryEnterpriseLevelAreaList(context, 0, 0, 0, new QryEnterpriseLevelAreaList());
        }

        contactLastTimeStamp = utils.getContactLastTimeStamp();
        /**
         * 获取通讯录列表数据，必须 在这个页面或者之前页面获取，因为ContactActivity页面在后面获取的，
         * 但是可能能有访问到ContactActivity页面，这是创建群组时会出问题，因为没有通讯录，而创建群组的页面逻辑是从数据库
         * 取出通讯录联系人
         */
        NewActionHelp.qryEnterpriseAddressBookList(context, contactLastTimeStamp, new GetAddressBookListHandler());
    }

    public class EnterpriseAreaCompanyListHandler
            extends
            ObjectHttpResponseHandler<AreaBean> {

        @Override
        public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
            android.util.Log.e("通讯录改造失败", s);
            listView.setAdapter(null);
        }

        @Override
        public void onSuccess(int code, Header[] headers, AreaBean data, String s) {
            android.util.Log.e("通讯录改造成功", s);
            QyreaderPerferencesUtil.getInstance(context, "0").setAreaLastTimeStamp(data.getLastTimeStamp());
            newAreaBean = data;
            listView.setAdapter(new AreaAdapterForNet(bActivity, newAreaBean.getAreaList()));
            GreendaoDBManager.deleteAll();
            for (int i = 0; i < data.getAreaList().size(); i++) {
                AreaBean.ProvinceBean provinceBean = data.getAreaList().get(i);
                GreendaoDBManager.insertArea(provinceBean);
                for (int j = 0; j < data.getAreaList().get(i).getList().size(); j++) {
                    AreaBean.ProvinceBean.CityBean cityBean = data.getAreaList().get(i).getList().get(j);
                    GreendaoDBManager.insertArea(cityBean);
                    for (int m = 0; m < data.getAreaList().get(i).getList().get(j).getList().size(); m++) {
                        AreaBean.ProvinceBean.CityBean.DistrictBean districtBean = data.getAreaList().get(i).getList().get(j).getList().get(m);
                        GreendaoDBManager.insertArea(districtBean);
                        for (int n = 0; n < data.getAreaList().get(i).getList().get(j).getList().get(m).getList().size(); n++) {
                            AreaBean.ProvinceBean.CityBean.DistrictBean.CompBean compBean = data.getAreaList().get(i).getList().get(j).getList().get(m).getList().get(n);
                            GreendaoDBManager.insertArea(compBean);
                        }
                    }
                }
            }
        }

        @Override
        public Type getType() {
            return new TypeToken<AreaBean>() {
            }.getType();
        }
    }

    public class QryEnterpriseLevelAreaList
            extends
            ObjectHttpResponseHandler<AreaBean2> {

        @Override
        public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
            android.util.Log.e("通讯录改造失败2", s);
            List<AreaBeanModle> list = GreendaoDBManager.queryAreaList("n");
            listView.setAdapter(new AreaAdapterForDB(bActivity, list, 1));
        }

        @Override
        public void onSuccess(int code, Header[] headers, AreaBean2 data, String s) {
            List<AreaBeanModle> list = new ArrayList<>();
            for (int i = 0; i < data.getAreaList().size(); i++) {
                if (data.getAreaList().get(i).getIsDelete().equals("n")) {
                    list.add(data.getAreaList().get(i));
                }
            }
            listView.setAdapter(new AreaAdapterForDB(bActivity, list, 1));
            GreendaoDBManager.deleteArea(1);
            GreendaoDBManager.insertAreaList(data.getAreaList());
        }

        @Override
        public Type getType() {
            return new TypeToken<AreaBean2>() {
            }.getType();
        }
    }

    public class GetYellowPageHandler
            extends
            ObjectHttpResponseHandler<ContactYellowPageInfo> {

        @Override
        public Type getType() {
            return new TypeToken<ContactYellowPageInfo>() {
            }.getType();
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {

        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, ContactYellowPageInfo arg2, String arg3) {
            if (arg2 != null) {
                ypUrl = arg2.getUrl();
            }
        }
    }


    private void setListener() {
        rlYellowPage.setOnClickListener(this);
        rlChatGroup.setOnClickListener(this);
        tvSearch.setOnClickListener(this);

    }

    /**
     * 下拉刷新
     */
    private void refrush() {
        listView.setVisibility(View.GONE);
        initData();
    }

    private void findView() {
        contentView = (PullToRefreshScrollView) curMyView.findViewById(R.id.contact_psview);
        PullToRefreshUtil.initLabel(bActivity, contentView);
        tvSearch = (TextView) curMyView.findViewById(R.id.et_contact_search);
        rlChatGroup = (RelativeLayout) curMyView.findViewById(R.id.rl_chat_groups);
        rlYellowPage = (RelativeLayout) curMyView.findViewById(R.id.rl_chat_yellow_page);
        listView = (MyListView) curMyView.findViewById(R.id.contacts_list);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object obj = parent.getItemAtPosition(position);
                if (obj instanceof AreaBean.ProvinceBean) {
                    AreaBean.ProvinceBean provinceBean = (AreaBean.ProvinceBean) obj;
                    Intent intent = new Intent(bActivity, AreaSelectActivity.class);
                    intent.putExtra("name", provinceBean.getProvinceName());
                    intent.putExtra("id_p", provinceBean.getProvinceId());
                    intent.putExtra("id_c", provinceBean.getCityId());
                    intent.putExtra("id_a", provinceBean.getAreaId());
                    intent.putExtra("dataType", provinceBean.getDataType());
                    bActivity.startActivity(intent);
                } else {//obj instanceof AreaBeanModle
                    AreaBeanModle areaBeanModle = (AreaBeanModle) obj;
                    Intent intent = new Intent(bActivity, AreaSelectActivity.class);
                    intent.putExtra("name", areaBeanModle.getProvinceName());
                    intent.putExtra("id_p", areaBeanModle.getProvinceId());
                    intent.putExtra("id_c", areaBeanModle.getCityId());
                    intent.putExtra("id_a", areaBeanModle.getAreaId());
                    intent.putExtra("dataType", areaBeanModle.getDataType());
                    bActivity.startActivity(intent);
                }
            }
        });
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        //		initData();
        SessionPage.isFirstIn = 1;
        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {

    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_chat_yellow_page:
                Intent ypIntent = new Intent(bActivity, CommonWebActivity.class);
                ypIntent.putExtra(DefaultConsts.title_s, "电话黄页");
                ypIntent.putExtra(DefaultConsts.req_url_s, ypUrl);
                bActivity.startActivity(ypIntent);
                break;

            case R.id.rl_chat_groups:
                Intent groupIntent = new Intent(bActivity, ContactGroupActivity.class);
                groupIntent.putExtra("fromType", "contactList");
                //				Intent groupIntent = new Intent(bActivity, ContactMainActivity.class);
                bActivity.startActivity(groupIntent);
                break;
            case R.id.et_contact_search:
                Intent searchIntent = new Intent(bActivity, ContactSearchActivity.class);
                bActivity.startActivity(searchIntent);
                break;
            default:
                break;
        }
    }

    public class GetAddressBookListHandler extends ObjectHttpResponseHandler<ContactBean> {
        @Override
        public Type getType() {
            return new TypeToken<ContactBean>() {
            }.getType();
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
        }

        @Override
        public void onSuccess(final int arg0, Header[] arg1, final ContactBean arg2, String arg3) {
            Log.e("通讯录具体员工", arg3);
            lastTimeStamp = arg2.getLastTimeStamp();
            utils.setContactLastTimeStamp(lastTimeStamp);
            if (arg2 != null && arg2.getGroupList() != null && arg2.getGroupList().size() > 0) {
                new Thread() {
                    @Override
                    public void run() {
                        groups = arg2.getGroupList();
                        putDataToDB();
                    }
                }.start();
            } else {
                handler.sendEmptyMessage(REFRESH_DATA);
            }
        }
    }

    /**
     * 数据库存储
     */
    private void putDataToDB() {
        handler.sendEmptyMessage(PROGRESS_SHOW);
        for (ContactSuperBean group : groups) {
            if (groupDao.getById(group.getGroupId()) != null) {
                groupDao.update(group);
            } else {
                groupDao.add(group);
            }
            for (com.ciko.code.logic.bean.ContactBookInfo contactBookInfo : group.getAddressBookList()) {
                if (addressBookInfoDao.getById(contactBookInfo.getContactId(), group.getGroupId()) != null) {
                    addressBookInfoDao.update(contactBookInfo);
                } else {
                    addressBookInfoDao.add(contactBookInfo);
                }
            }
        }
        handler.sendEmptyMessage(PROGRESS_HIDE);
        handler.sendEmptyMessage(REFRESH_DATA);

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PROGRESS_SHOW:
                    progressDialog = ProgressDialog.show(context, "", "正在初始化...");
                    break;
                case PROGRESS_HIDE:
                    progressDialog.dismiss();
                    break;
            }
        }
    };
}
